<template>
  <div>
    <!-- 1.页面展示区域 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 1.1 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true">
          <el-form-item label="文章分类">
            <el-select
              placeholder="请选择分类"
              size="small"
              v-model="query.cate_id"
            >
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select
              placeholder="请选择状态"
              size="small"
              v-model="query.state"
            >
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getArtList"
              >筛选</el-button
            >
            <el-button type="info" size="small" @click="doReset"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          size="small"
          class="btn-pub"
          @click="dialogVisible = true"
          >发表文章</el-button
        >
      </div>
      <!-- 1.2 文章表格区域 -->
      <el-table :data="artList">
        <el-table-column label="文章标题">
          <template v-slot="scope">
            <el-link
              type="primary"
              :underline="false"
              @click="getArticleInfo(scope.row.id)"
              >{{ scope.row.title }}</el-link
            >
          </template>
        </el-table-column>
        <el-table-column label="文章分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间" prop="pub_date">
          <template v-slot="scope">
            {{ getDate(scope.row.pub_date) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作" prop="">
          <template v-slot="scope">
            <el-button type="danger" @click="doDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 1.3 分页区域 -->
      <el-pagination
        @size-change="doSizeChange"
        @current-change="doCurrentChange"
        :page-sizes="[2, 5, 10, 15, 20]"
        :page-size="query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 全屏新增文章对话框 -->
    <!-- 2.发表文章对话框 -->
    <el-dialog title="发表文章" :visible.sync="dialogVisible" fullscreen>
      <!-- 对话框内容 -->
      <el-form label-width="100px">
        <!-- 2.1文章标题 -->
        <el-form-item label="文章标题">
          <el-input
            placeholder="请输入标题"
            v-model="formData.title"
          ></el-input>
        </el-form-item>
        <!-- 2.2文章分类 -->
        <el-form-item label="文章分类">
          <el-select
            placeholder="请选择分类"
            style="width: 100%;"
            v-model="formData.cate_id"
          >
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :value="item.id"
              :label="item.cate_name"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 2.3文章内容 -->
        <el-form-item label="文章内容">
          <quillEditor v-model="formData.content"></quillEditor>
        </el-form-item>
        <!-- 2.4文章封面 -->
        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img
            src="@/assets/images/cover.jpg"
            alt=""
            class="cover-img"
            ref="imgRef"
          />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input
            type="file"
            style="display: none;"
            accept="image/*"
            ref="iptRef"
            @change="doFileChange"
          />
          <!-- 选择封面的按钮 -->
          <el-button type="primary" plain @click="$refs.iptRef.click()"
            >+ 选择封面</el-button
          >
        </el-form-item>
        <!-- 2.5底部按钮 -->
        <el-form-item>
          <el-button type="primary" @click="addArticle('已发布')"
            >发布</el-button
          >
          <el-button type="info" @click="addArticle('草稿')"
            >存为草稿</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 3.文章信息对话框 -->
    <el-dialog title="文章详情" :visible.sync="infoDialogVisible">
      <h1 class="title">{{ articleInfo.title }}</h1>
      <div class="info">
        <h3>作者: {{ articleInfo.nickname || articleInfo.username }}</h3>
        <h3>发布时间: {{ getDate(articleInfo.pub_date) }}</h3>
        <h3>所属分类: {{ articleInfo.cate_name }}</h3>
        <h3>状态: {{ articleInfo.state }}</h3>
      </div>
      <!-- 分割线 -->
      <el-divider></el-divider>
      <img
        :src="`http://big-event-vue-api-t.itheima.net${articleInfo.cover_img}`"
        alt=""
      />
      <div v-html="articleInfo.content"></div>
    </el-dialog>
  </div>
</template>

<script>
// 导入第三方富文本组件
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'

// 导入moment.js
import moment from 'moment'

export default {
  name: 'ArtList',
  components: {
    quillEditor
  },
  data () {
    return {
      // 新增对话框显示布尔值
      dialogVisible: false,
      // 传参参数
      query: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      // 文章列表
      artList: [],
      total: 0,
      // 表单数据
      formData: {
        title: '',
        cate_id: '',
        content: '',
        state: '',
        cover_img: ''
      },
      // 分类列表
      cateList: [],
      // 文章详情对话框布尔值
      infoDialogVisible: false,
      // 文章详情内容
      articleInfo: {}
    }
  },
  // methods:事件处理函数
  methods: {
    // 文章列表
    async getArtList () {
      const res = await this.$axios.get('/my/article/list', {
        params: this.query
      })
      this.artList = res.data.data
      this.total = res.data.total
    },
    // 页数改变
    doSizeChange (size) {
      this.query.pagesize = size
      // 页码显示第一页
      this.query.pagenum = 1
      // 刷新页面
      this.getArtList()
    },
    // 页码改变
    doCurrentChange (page) {
      this.query.pagenum = page
      this.getArtList()
    },
    // 转换时间
    getDate (date) {
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    // 文件预览
    doFileChange (e) {
      // 获取文件
      const file = e.target.files[0]
      // 把file转换成url
      const url = URL.createObjectURL(file)
      // 把url赋值给img
      this.$refs.imgRef.src = url
      // 将file对象绑定到data中
      this.formData.cover_img = file
    },
    // 添加文章
    async addArticle (state) {
      // 将state绑定到data中
      this.formData.state = state
      // 将data中的数据添加到FormData中
      const fd = new FormData()
      // 遍历this.FormData 然后fd.append()添加到fd中
      /* 原因: 带二进制的数据都需要通过FormData来发送  不能直接发js对象处理: 遍历js对象 把js对象数据append()到fd对象中
       */
      for (let k in this.formData) {
        fd.append(k, this.formData[k])
      }
      // 发送ajax
      const res = await this.$axios.post('/my/article/add', fd)
      // 根据返回结果操作
      if (res.data.code === 0) {
        // 提示
        this.$message.success(res.data.message)
        // 弹窗消失
        this.dialogVisible = false
        // 刷新页面
        this.getArtList()
      } else {
        this.$message.error(res.data.message)
      }
    },
    // 重置
    doReset () {
      // 传参参数恢复默认文本
      this.query = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      // 刷新页面
      this.getArtList()
    },
    // 获取文章详情
    async getArticleInfo (id) {
      // 对话框出现
      this.infoDialogVisible = true
      // 发送ajax
      const res = await this.$axios.get('/my/article/info', { params: { id } })
      // 将返回的值绑定到data中
      this.articleInfo = res.data.data
    },
    // 删除文章
    async doDelete (id) {
      // 发送ajax
      const res = await this.$axios.delete('/my/article/info', {
        params: { id }
      })
      // 处理响应结果
      if (res.data.code === 0) {
        this.$message.success(res.data.message)
        this.infoDialogVisible = false
        if (this.total % this.query.pagesize === 1) {
          this.query.pagenum--
        }
        this.getArtList()
      } else {
        this.$message.error(res.data.message)
      }
    }
  },
  async created () {
    // 获取文章列表
    this.getArtList()
    // 获取分类列表
    const res = await this.$axios.get('/my/cate/list')
    // 绑定到data中
    this.cateList = res.data.data
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}

/deep/ .ql-editor {
  min-height: 300px;
}

// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

.el-pagination {
  margin-top: 15px;
}

.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
